package org.javaboy.remember_me_demo.service;

import org.javaboy.remember_me_demo.mapper.UserMapper;
import org.javaboy.remember_me_demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserService implements UserDetailsService, UserDetailsPasswordService {
    @Autowired
    UserMapper userMapper;
    /**
     * 当用户登录的时候，会自动触发这个方法的执行，通过这个方法，根据用户名去数据库中查询用户对象
     * @param username the username identifying the user whose data is required.
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User u = userMapper.loadUserByUsername(username);
        if (u == null) {
            //说明用户名不存在
            throw new UsernameNotFoundException("用户不存在");
        }
        return u;
    }

    /**
     * 这个就是密码升级方法，每当用户登录的时候，系统都会去判断用户密码是否需要升级，如果需要升级，则会触发这个方法，然后在这个方法中完成密码升级
     * @param user the user to modify the password for
     * @param newPassword the password to change to, encoded by the configured
     * {@code PasswordEncoder}
     * @return
     */
    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        userMapper.updatePassword(user.getUsername(), newPassword);
        return user;
    }
}
